package com.qing;

import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;

public class Demo5 {

	public static void main(String[] args) {
//		这似乎是利用并行处理的好机会，特别是n很大的时候。那怎么入手呢？
//		你要对结果变量进行同步吗？
//		用多少个线程呢？
//		谁负责生成数呢？
//		谁来做加法呢？

		long n=10_000_000;
		Long startTime1=System.currentTimeMillis();
		sequentialSum(n);
		System.out.println(System.currentTimeMillis()-startTime1); //287

		Long startTime2=System.currentTimeMillis();
		iterativeSum(n);
		System.out.println(System.currentTimeMillis()-startTime2); //5



		Long startTime3=System.currentTimeMillis();
		sequentialParallelSum(n);
		System.out.println(System.currentTimeMillis()-startTime3); //2203

		System.out.println("处理器数量："+Runtime.getRuntime().availableProcessors());

		System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","12");

	}

	public static long sequentialSum(long n){
		return Stream.iterate(1L,i->i+1).limit(n)
				.sequential() //将流转为顺序执行
				.reduce(0L,Long::sum);
	}

	public static long sequentialParallelSum(long n){
		return Stream.iterate(1L,i->i+1).limit(n).
				parallel()  //将流转为并行
				.reduce(0L,Long::sum);
	}

	public static long iterativeSum(long n){
		long result=0;
		for (long i = 1L; i <= n; i++) {
			result+=i;
		}
		return result;
	}


}
